package LeetCode_SingleLinkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description:寻找链表的公共节点
 * User: 阿宾
 * Date: 2024-11-08
 * Time: 07:53
 */
public class Demo7 {
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static int length(ListNode list){
        int count = 0;
        while(list != null){
            count++;
            list = list.next;
        }
        return count;
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        /*if(headA == null || headB == null){
            return null;
        }*/
        int l1 = length(headA);
        int l2 = length(headB);
        ListNode a;
        ListNode b;
        for (a = headA; l1 > l2; l1--) {
            a = a.next;
        }
        for (b = headB; l2 > l1; l2--) {
            b = b.next;
        }
        /*while (a != null && a.next != b.next){
            a = a.next;
            b = b.next;
        }
        return a.next;*/
        //上述判断逻辑有问题，如果链表长度为1的时候，返回a.next是null
        while (a != null && b != null){
            if(a == b){
                return a;
            }
            a = a.next;
            b = b.next;
        }
        return null;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(4, new ListNode(1,new ListNode(8,new ListNode(4,new ListNode(5)))));
        ListNode l2 = new ListNode(12, new ListNode(23,new ListNode(56,new ListNode(23,new ListNode(12)))));
        //Boolean result = chkPalindrome(l1);
        //System.out.println(result);
        System.out.println(length(l1));
    }
}
